import { add, del, list, update } from '@/services/system/role';
import { ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Modal, Tag, message } from 'antd';
import React, { useRef, useState } from 'react';
import UpdateForm from './components/UpdateForm';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: SYSTEM.Role) => {
  const hide = message.loading('正在添加');
  try {
    await add({ ...fields });
    hide();
    message.success('Added successfully');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: SYSTEM.Role) => {
  const hide = message.loading('Configuring');
  try {
    await update({ ...fields });
    hide();

    message.success('Configuration is successful');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

const { confirm } = Modal;

const RoleList: React.FC = () => {
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [editModalOpen, handleEditModalOpen] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<SYSTEM.Role>();

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const showDelConfirm = (id: number) => {
    confirm({
      title: intl.formatMessage({
        id: 'pages.delete.tip.title',
        defaultMessage: 'Do you want to delete these items?',
      }),
      icon: <ExclamationCircleFilled />,
      async onOk() {
        try {
          await del({ id: id });
          if (actionRef.current) {
            actionRef.current.reload();
          }
          message.success(
            intl.formatMessage({
              id: 'pages.delete.success',
              defaultMessage: 'Delete success',
            }),
          );
        } catch (error) {
          message.error(
            intl.formatMessage({
              id: 'pages.delete.failed',
              defaultMessage: 'Delete failed, please try again!',
            }),
          );
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const columns: ProColumns<SYSTEM.Role>[] = [
    {
      title: <FormattedMessage id="pages.id" defaultMessage="Id" />,
      dataIndex: 'id',
      width: 120,
      search: false,
    },
    {
      title: <FormattedMessage id="pages.user.role.name" defaultMessage="Role Name" />,
      dataIndex: 'name',
      width: 120,
    },
    {
      title: <FormattedMessage id="pages.status" defaultMessage="Status" />,
      dataIndex: 'enable',
      hideInForm: true,
      width: 120,
      valueEnum: {
        true: {
          text: <FormattedMessage id="pages.status.enable" defaultMessage="Enable" />,
          status: 'Success',
        },
        false: {
          text: <FormattedMessage id="pages.status.disable" defaultMessage="Disable" />,
          status: 'Error',
        },
      },
    },
    {
      title: (
        <FormattedMessage id="pages.user.role.permission" defaultMessage="Contain Permission" />
      ),
      dataIndex: 'permissions',
      hideInForm: true,
      hideInSearch: true,
      render: (dom, record: any) => {
        if (record.permissions) {
          return (
            <>
              {record?.permissions?.length > 0 &&
                record?.permissions?.map((item: any) => {
                  return (
                    <Tag color="orange" key={item.id}>
                      {item.name}
                    </Tag>
                  );
                })}
            </>
          );
        } else {
          return <>{dom}</>;
        }
      },
    },
    {
      title: <FormattedMessage id="pages.createDate" defaultMessage="Create Date" />,
      dataIndex: 'createDate',
      valueType: 'dateTime',
      width: 260,
      search: false,
    },
    {
      title: <FormattedMessage id="pages.option" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      width: 180,
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          onClick={() => {
            handleEditModalOpen(true);
            let permissionIds: any = [];
            record.permissions?.forEach((item) => {
              permissionIds.push(item.id);
            });
            record.permissionIds = permissionIds;
            setCurrentRow(record);
          }}
        >
          <FormattedMessage id="pages.edit" defaultMessage="Edit" />
        </Button>,
        <Button
          key="delete"
          type="link"
          disabled={!record.canDelete}
          danger
          onClick={() => {
            if (record.id) {
              showDelConfirm(record.id);
            }
          }}
        >
          <FormattedMessage id="pages.delete" defaultMessage="Delete" />
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.user.role.title',
          defaultMessage: 'Role List',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleEditModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.new" defaultMessage="New" />
          </Button>,
        ]}
        request={list}
        columns={columns}
      />
      <UpdateForm
        onSubmit={async (value) => {
          let success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleEditModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        setEditModalOpen={async (open) => {
          if (!open) {
            setCurrentRow(undefined);
          }
          handleEditModalOpen(open);
        }}
        editModalOpen={editModalOpen}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default RoleList;
